package edu.isquen.core.user.service;

import java.util.Collection;

import edu.isquen.core.base.dao.IBaseDAO;
import edu.isquen.core.base.service.BaseServiceImpl;
import edu.isquen.core.user.dao.UserDAO;
import edu.isquen.core.user.model.User;
import edu.isquen.util.CommUtil;
import edu.isquen.util.factory.DaoFactory;
import edu.isquen.web.exception.BaseException;

public class UserServiceImpl extends BaseServiceImpl implements UserService {
	
	private static final long serialVersionUID = 5064919065413459722L;
	@Override
	public IBaseDAO<?> getDao() throws Exception {
		// TODO Auto-generated method stub
		return DaoFactory.getDao(User.class.getName());
	}
	public User doLogin(String loginname, String loginpwd) throws Exception {
		if (!CommUtil.validateString(loginname)
				|| !CommUtil.validateString(loginpwd)) {
			return null;
		}
		return ((UserDAO) getDao()).login(loginname, CommUtil.encodeToMD5(loginpwd));
	}
	public User doSaveOrUpdate(User user) throws Exception {
		if (user == null) {
			return null;
		}
		if(user.getLoginpwd()==null){
			user.setLoginpwd("");
		}else{
			user.setLoginpwd(CommUtil.encodeToMD5(user.getLoginpwd()));
		}
		if (!CommUtil.validateString(user.getId())) {
			User forExamineUser = new User();
			forExamineUser.setLoginno(user.getLoginno());
			if (getDao().findByAny(forExamineUser).datas.size()<=0) {
				this.doCreate(user);
			}else{
				throw new BaseException("Name is exit..!");
			}
		} else {
			this.doUpdate(user);
		}
		return user;
	}
	@SuppressWarnings("unchecked")
	public Collection<User> getUsersByRole(String roleid) throws Exception {
		String sql="select * from t_user vo"
				+" where vo.id in ("
				+" select urs.userid from t_userroleset urs where urs.roleid='"+roleid+"'"
				+" )";
		return (Collection<User>)this.getDao().getDatasBySql(sql);
	}
	
	

}
